package com.diamond.web.listeners;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
import com.diamond.web.utils.SK;

/**
 * Shiro Session监听器
 * @author Diamond
 *
 */
public class NotifySessionListener implements SessionListener{
	static Logger log = Logger.getLogger(NotifySessionListener.class);
	private static Map<Serializable,Session> sessionMap = new HashMap<Serializable, Session>();
	
	@Override
	public void onStart(Session session) {
		sessionMap.put(session.getId(), session);
		log.info("session start:"+session.getId());
	}
	
	@Override
	public void onStop(Session session) {
		sessionMap.remove(session.getId());
		log.info("session stop:"+session.getId());
	}
	
	@Override
	public void onExpiration(Session session) {
		sessionMap.remove(session.getId());
		log.info("session expiration:"+session.getId());
	}

	/**
	 * 将消息通知到每个登录的 用户里面
	 * @param key
	 * @param obj
	 */
	public static void notifyToSession(String key,Object obj) {
		for(Session session:sessionMap.values()){
			log.info("try to notify session:"+session.getId());
			if(session.getAttribute(SK.USER_INFO)!=null){
				log.info("has notify session:"+session.getId());
				session.setAttribute(key, obj);
			}
		}
	}
}
